import { getUserInfo, loginOut } from '@/api/login';
import router from '@/router';
const isDev = import.meta.env.VITE_APP_ENV === 'development';
const useUserStore = defineStore('user', {
  state: () => ({
    isLogin: false, // 是否已经登录
    userInfo: {}, // 用户信息
    permissions: [], // 用户当前拥有的权限，必须
    roles: [] // 至少有一个角色身份才能进入系统，必须，有些菜单和功能可能需要按角色处理，如SMT
  }),
  actions: {
    // todo 获取用户信息
    getInfo() {
      return new Promise(async (resolve, reject) => {
        try {
          // const { data: info } = await getUserInfo();
          const info = { name: '陈东', perms: ['role_a', 'role_b', 'role_c'] };
          this.isLogin = true;
          this.userInfo = info;
          this.permissions = info.perms || [];
          // 角色权限，至少有一个角色，否则会跳至无角色权限页面
          this.roles = ['admin'];
          resolve();
        } catch (err) {
          reject(err);
        }
      });
    },
    // 登录 oauth2页面会自动存储cookie
    login(url) {
      if (isDev) {
        const origin = location.href.split('#')[0];
        const params = {
          client_id: '7a093f16-b372-5c61-3c31-0e380fe94d6f', // todo 根据项目情况配置应用ID，实现本地登录
          response_type: 'code',
          state: 'random',
          redirect_uri: encodeURIComponent(
            `${origin}#/oauth2-callback?callback=${encodeURIComponent(
              url || location.href
            )}`
          )
        };
        const config = {
          // 测试环境权限系统配置
          test: {
            curl: 'https://test-oauth2.zx-tech.net/oauth2/auth',
            params: { ...params }
          },
          // 正式环境权限系统配置
          prod: {
            curl: 'https://oauth2.mundossp.com/oauth2/auth',
            params: { ...params }
          }
        }['test'];

        let linkUrl = `${config.curl}?`;
        Object.keys(config.params).forEach((key, index) => {
          if (index === 0) linkUrl += `${key}=${config.params[key]}`;
          else linkUrl += `&${key}=${config.params[key]}`;
        });
        window.open(linkUrl, '_self');
      } else {
        location.href = `/oauth2/login?callback=${encodeURIComponent(
          url || location.href
        )}`;
      }
    },
    // 退出系统
    logOut() {
      return new Promise(async (reslove, reject) => {
        try {
          loginOut();
          router.replace(`/login`);
          // 保留退出时的页面
          // router.replace(`/login?redirect=${location.href.split('#')[1]}`);
          reslove();
        } catch (err) {
          reject(err);
        }
      });
    }
  }
});

export default useUserStore;
